// httpserver.js
const http = require('http');
const fs = require('fs');
const path = require('path');

const PORT = 49527;
const FILE_DIR = path.join(__dirname, 'file'); // 本地文件夹路径

// 创建HTTP服务器
const server = http.createServer((req, res) => {
  const url = new URL(req.url, `http://${req.headers.host}`);
  const filePath = url.pathname;

  // 检查Accept头是否包含'authentic'
  const acceptHeader = req.headers.accept || '';
  if (!acceptHeader.includes('authentic')) {
    res.writeHead(403, { 'Content-Type': 'text/plain' });
    res.end('Forbidden: Accept header does not contain "authentic"');
    return;
  }

  // 处理 /login 请求
  if (filePath === '/login') {
    let body = '';
    req.on('data', chunk => {
      body += chunk.toString();
    });
    req.on('end', () => {
      try {
        const { username, password } = JSON.parse(body);

        // 简单的验证逻辑（可以根据实际需求修改）
        if (username === '' && password === '1') {
          res.writeHead(200, { 'Content-Type': 'application/json' });
          res.end(JSON.stringify({ message: 'Login successful', token: 'your-auth-token' }));
        } else if (username === 'admin' && password === 'password') {
          res.writeHead(200, { 'Content-Type': 'application/json' });
          res.end(JSON.stringify({ message: 'Login successful', token: 'your-auth-token' }));
        } else {
          res.writeHead(401, { 'Content-Type': 'application/json' });
          res.end(JSON.stringify({ message: 'Invalid credentials' }));
        }
      } catch (error) {
        res.writeHead(400, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ message: 'Invalid request body' }));
      }
    });
    return;
  }

  if (filePath.startsWith('/file/')) {
    const fileName = filePath.substring('/file/'.length);
    const fullPath = path.join(FILE_DIR, fileName);

    // 检查文件是否存在
    fs.access(fullPath, fs.constants.F_OK, (err) => {
      if (err) {
        res.writeHead(404, { 'Content-Type': 'text/plain' });
        res.end('File not found');
      } else {
        // 读取文件并返回
        const fileStream = fs.createReadStream(fullPath);
        fileStream.on('open', () => {
          res.writeHead(200, { 'Content-Type': 'image/jpeg' }); // 假设文件是jpg格式
          fileStream.pipe(res);
        });
        fileStream.on('error', (err) => {
          res.writeHead(500, { 'Content-Type': 'text/plain' });
          res.end('Internal Server Error');
        });
      }
    });
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('Not Found');
  }
});

// 导出启动服务器的函数
function startHttpServer() {
  server.listen(PORT, () => {
    console.log(`HTTP server is running on http://localhost:${PORT}`);
  });
}

module.exports = { startHttpServer };